const { User } = require('../db');
const { randomString } = require('../utils');
const dayjs = require('dayjs');
const timezone = require('dayjs/plugin/timezone');
const utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.tz.setDefault('PRC');
module.exports = {
  userController(app) {
    /** 新建用户 */
    app.get('/api/user/queryAndCreate', async (req, res) => {
      const openId = req.headers['x-wx-openid'] || req.query?.openId;
      if (!openId) {
        res.send({ code: -1, msg: '缺少参数openId' });
        return;
      }
      try {
        const userRlt = (await User.findAll({
          where: { openId },
        }))?.map(_ => _.dataValues);
        let rlt = userRlt?.[0];
        if (!rlt) {
          rlt = await User.create({ openId: openId, name: randomString(8) });
        } else {
          const lastLoginTime = dayjs.tz().toDate();
          await User.update({
            lastLoginTime: lastLoginTime,
          }, {
            where: { openId },
          });
          rlt.lastLoginTime = lastLoginTime;
        }
        res.send({ code: 200, data: rlt, msg: 'success' });
      } catch (e) {
        res.send({ code: -1, msg: `${ e.message }` });
      }
    });
    /** OpenId查询用户 */
    app.get('/api/user/queryByOpenId', async (req, res) => {
      const openId = req.headers['x-wx-openid'] || req.query?.openId;
      if (!openId) {
        res.send({ code: -1, msg: '缺少参数openId' });
        return;
      }
      try {
        const userRlt = (await User.findAll({
          where: { openId },
        }))?.map(_ => _.dataValues);
        let rlt = userRlt?.[0];
        res.send({ code: 200, data: rlt, msg: 'success' });
      } catch (e) {
        res.send({ code: -1, msg: `${ e.message }` });
      }
    });
    // 修改打印次数
    app.post('/api/user/changePrintTimes', async (req, res) => {
      const openId = req.headers['x-wx-openid'] || req.body?.openId;
      const { diff = 0, times = 0, type = '' } = req.body;
      const _diff = Number(diff);
      if (!openId) {
        res.send({ code: -1, msg: '缺少参数openId' });
        return;
      }
      if (!['ygo', 'rd'].includes(type)) {
        res.send({ code: -1, msg: '无效的type' });
        return;
      }
      try {
        const userRlt = (await User.findAll({
          where: { openId },
        }))?.map(_ => _.dataValues);
        let rlt = userRlt?.[0];
        if (!rlt) {
          res.send({ code: -1, msg: `找不到该用户` });
          return;
        }
        let targetTimes = times;
        if (_diff) {
          targetTimes = Math.max(
            (type === 'ygo' ? rlt?.ygoPrintTimes : type === 'rd' ? rlt?.rdPrintTimes : 0) + _diff,
            0,
          );
        }
        const updateItem = type === 'ygo'
          ? { ygoPrintTimes: targetTimes }
          : type === 'rd'
            ? { rdPrintTimes: targetTimes }
            : {};
        await User.update(updateItem, {
          where: { openId },
        });
        res.send({ code: 200, data: true, msg: `success` });
      } catch (e) {
        res.send({ code: -1, msg: `${ e.message }` });
      }
    });
    // 增加总打印数
    app.post('/api/user/addTotalPrintTimes', async (req, res) => {
      const openId = req.headers['x-wx-openid'] || req.body?.openId;
      const { type = '' } = req.body;
      if (!openId) {
        res.send({ code: -1, msg: '缺少参数openId' });
        return;
      }
      if (!['ygo', 'rd'].includes(type)) {
        res.send({ code: -1, msg: '无效的type' });
        return;
      }
      try {
        const userRlt = (await User.findAll({
          where: { openId },
        }))?.map(_ => _.dataValues);
        let rlt = userRlt?.[0];
        if (!rlt) {
          res.send({ code: -1, msg: `找不到该用户` });
          return;
        }
        // let targetTimes = times;
        // if (_diff) {
        //   targetTimes = Math.max(
        //     (type === 'ygo' ? rlt?.ygoPrintTimes : type === 'rd' ? rlt?.rdPrintTimes : 0) + _diff,
        //     0,
        //   );
        // }
        const updateItem = type === 'ygo'
          ? { ygoTotalPrintTimes: rlt.ygoTotalPrintTimes + 1 }
          : type === 'rd'
            ? { rdTotalPrintTimes: rlt.rdTotalPrintTimes + 1 }
            : {};
        await User.update(updateItem, {
          where: { openId },
        });
        res.send({ code: 200, data: true, msg: `success` });
      } catch (e) {
        res.send({ code: -1, msg: `${ e.message }` });
      }
    });
    // 修改用户名
    app.post('/api/user/changeName', async (req, res) => {
      const openId = req.headers['x-wx-openid'] || req.body?.openId;
      const { name = '' } = req.body;
      if (!openId) {
        res.send({ code: -1, msg: '缺少参数openId' });
        return;
      }
      if (!name) {
        res.send({ code: -1, msg: '缺少name' });
        return;
      }
      if (name?.length > 10) {
        res.send({ code: -1, msg: '用户名不能超过10个字符' });
        return;
      }
      try {
        await User.update({ name }, {
          where: { openId },
        });
        res.send({ code: 200, data: true, msg: `success` });
      } catch (e) {
        res.send({ code: -1, msg: `${ e.message }` });
      }
    });
  },
};
